package com.zwcl.glass.tools.controller;

import com.zwcl.common.component.upload.cloud.CloudStorageService;
import com.zwcl.common.component.upload.cloud.OSSFactory;
import com.zwcl.common.component.upload.cloud.QcloudCloudStorageService;
import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.common.core.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/upload")
public class UploadFileController {

    @Autowired
    private OSSFactory ossFactory;

    @PostMapping("/uploadFiles")
    public ApiResult uploadFiles(@Param("files") MultipartFile[] files) {
        if(files == null || files.length < 1){
            return ApiResult.fail("文件不能为空！");
        }
        CloudStorageService qcloudCloudStorageService=ossFactory.build();
        Map<String, List<String>> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        Arrays.stream(files).forEach(file ->{
            //String fileName = Calendar.getInstance().getTimeInMillis()+"";
            if(StringUtils.isNotBlank(file.getOriginalFilename())){
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                try {
                    list.add(qcloudCloudStorageService.uploadSuffix(file.getBytes(), suffix));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        map.put("url",list);
        return ApiResult.ok(map);
    }

    @PostMapping("/uploadFile")
    public ApiResult<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if(file == null){
            return ApiResult.fail("文件不能为空！");
        }
        CloudStorageService qcloudCloudStorageService=ossFactory.build();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            String  url = qcloudCloudStorageService.uploadSuffix(file.getBytes(), suffix);
            return ApiResult.ok(url);
        }catch (IOException e) {
            throw  new BusinessException("文件上传失败");
        }
    }
}
